/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.corticon.client.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

/**
 * Misc. <code>Map</code> support functionality.
 *
 * @author Ali Yang
 */
public class MapUtils {

    public static Map removeKeyPrefix(Map originalMap, String prefix) {

        Map map = new HashMap(originalMap.size());

        for (Iterator iter = originalMap.keySet().iterator(); iter.hasNext();) {
            String key = iter.next().toString();
            String newKey = StringUtils.removeStart(key, prefix);
            Object value = originalMap.get(key);
            map.put(newKey, value);
        }

        return map;
    }

    public static Map<String, String> nameValuePairStringToMap(
            String nameValuePairString) {
        return delimitedNameValuesStringToMap(nameValuePairString, "&", "=");
    }

    public static Map<String, String> delimitedNameValuesStringToMap(
            String delimitedNameValueString, String delimiter,
            String nameValueDelimiter) {

        Map<String, String> map = new HashMap<String, String>();
        String nameValuePairs[] = delimitedNameValueString.split(delimiter);

        for (String nameValuePair : nameValuePairs) {

            String tokens[] = StringUtils.split(nameValuePair,
                    nameValueDelimiter);
            String name = tokens[0];
            String value = null;

            if (tokens.length > 1) {
                value = tokens[1];
            }

            map.put(name, value);
        }

        return map;
    }
}